using System;
using System.Runtime.CompilerServices;
using System.Web;
using System.Xml;

namespace MyWebPagesStarterKit.Sitemaps.Utilities
{
    public abstract class XmlResponseHandlerBase : Handler, IHttpHandler
    {
        public event EventHandler Error;

        protected XmlResponseHandlerBase()
        {
        }

        protected virtual void OnError(EventArgs e)
        {
            if (this.Error != null)
            {
                this.Error(this, e);
            }
        }

        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            base.Context = context;
            try
            {
                XmlResponse(context.Response, new Action<XmlTextWriter>(this.WriteResult));
            }
            catch (Exception exception)
            {
                context.AddError(exception);
                this.OnError(EventArgs.Empty);
                if (context.Error != null)
                {
                    throw new HttpUnhandledException("blah", exception);
                }
            }
        }

        protected abstract void WriteResult(XmlTextWriter result);
        public static void XmlResponse(HttpResponse response, Action<XmlTextWriter> writeAction)
        {
            response.ClearHeaders();
            response.ClearContent();
            response.ContentType = "text/xml";
            XmlTextWriter writer = new XmlTextWriter(response.Output);
            writeAction(writer);
            writer.Flush();
        }

        bool IHttpHandler.IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
